<template>
  <div class="cart-page">
    <div class="container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>购物车</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="cart-content">
        <!-- 购物车标题 -->
        <div class="cart-header">
          <h1>我的购物车</h1>
          <div class="cart-summary">
            <span>共 {{ cartStore.totalCount }} 件商品</span>
            <span class="total-price">总计: ¥{{ cartStore.totalPrice.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 购物车列表 -->
        <div v-loading="cartStore.loading">
          <div v-if="cartStore.cartItems.length > 0" class="cart-items">
            <el-card v-for="item in cartStore.cartItems" :key="item.id" class="cart-item">
              <el-row :gutter="20" align="middle">
                <!-- 商品图片 -->
                <el-col :span="4">
                  <div class="item-image">
                    <img
                      :src="item.imageError ? '/placeholder.jpg' : (item.productImage || '/placeholder.jpg')"
                      :alt="item.productName"
                      @error="handleImageError(item)"
                    />
                  </div>
                </el-col>

                <!-- 商品信息 -->
                <el-col :span="8">
                  <div class="item-info">
                    <h3 class="item-name" @click="goToProduct(item.productId)">
                      {{ item.productName }}
                    </h3>
                    <p class="item-price">单价: ¥{{ item.productPrice }}</p>
                  </div>
                </el-col>

                <!-- 数量控制 -->
                <el-col :span="4">
                  <div class="quantity-control">
                    <el-input-number
                      v-model="item.quantity"
                      :min="1"
                      :max="999"
                      size="small"
                      @change="(value) => updateQuantity(item.id, value)"
                    />
                  </div>
                </el-col>

                <!-- 小计 -->
                <el-col :span="4">
                  <div class="item-subtotal">
                    <span class="subtotal-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                  </div>
                </el-col>

                <!-- 操作按钮 -->
                <el-col :span="4">
                  <div class="item-actions">
                    <el-button
                      type="danger"
                      size="small"
                      @click="removeItem(item.id)"
                      :loading="removingItem === item.id"
                    >
                      删除
                    </el-button>
                  </div>
                </el-col>
              </el-row>
            </el-card>

            <!-- 购物车底部操作 -->
            <div class="cart-footer">
              <div class="cart-actions">
                <el-button @click="clearCart" type="warning" :loading="clearing">
                  清空购物车
                </el-button>
                <el-button @click="$router.push('/products')" type="default">
                  继续购物
                </el-button>
              </div>
              
              <div class="checkout-section">
                <div class="checkout-summary">
                  <div class="summary-item">
                    <span>商品总数:</span>
                    <span>{{ cartStore.totalCount }} 件</span>
                  </div>
                  <div class="summary-item">
                    <span>商品总价:</span>
                    <span class="total-price">¥{{ cartStore.totalPrice.toFixed(2) }}</span>
                  </div>
                </div>
                
                <el-button
                  type="primary"
                  size="large"
                  @click="checkout"
                  :disabled="cartStore.cartItems.length === 0"
                >
                  去结算
                </el-button>
              </div>
            </div>
          </div>

          <!-- 空购物车 -->
          <el-empty
            v-else
            description="购物车是空的"
            :image-size="200"
          >
            <el-button type="primary" @click="$router.push('/products')">
              去购物
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCartStore } from '@/stores/cart'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 响应式数据
const removingItem = ref(null)
const clearing = ref(false)

// 计算属性
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 方法
const updateQuantity = async (cartItemId, quantity) => {
  try {
    await cartStore.updateItemQuantity(cartItemId, quantity)
  } catch (error) {
    console.error('更新数量失败:', error)
  }
}

const removeItem = async (cartItemId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    removingItem.value = cartItemId
    await cartStore.removeItemFromCart(cartItemId)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  } finally {
    removingItem.value = null
  }
}

const clearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    clearing.value = true
    await cartStore.clearAllItems()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
    }
  } finally {
    clearing.value = false
  }
}

const goToProduct = (productId) => {
  router.push(`/product/${productId}`)
}

const checkout = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 跳转到订单确认页面
  router.push('/order/confirm')
}

const handleImageError = (item) => {
  item.imageError = true
}

// 生命周期
onMounted(() => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  cartStore.fetchCartItems().then(() => {
    // 为每个购物车商品加 imageError 字段
    cartStore.cartItems.forEach(item => {
      if (item.imageError === undefined) item.imageError = false
    })
  })
})
</script>

<style scoped>
.cart-page {
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin-bottom: 30px;
}

.cart-content {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.cart-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.cart-summary {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #e74c3c;
}

.cart-items {
  padding: 20px;
}

.cart-item {
  margin-bottom: 15px;
}

.cart-item:last-child {
  margin-bottom: 0;
}

.item-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 4px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  padding: 0 10px;
}

.item-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-name:hover {
  color: #409eff;
}

.item-price {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.quantity-control {
  text-align: center;
}

.item-subtotal {
  text-align: center;
}

.subtotal-price {
  font-size: 16px;
  font-weight: bold;
  color: #e74c3c;
}

.item-actions {
  text-align: center;
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
}

.cart-actions {
  display: flex;
  gap: 10px;
}

.checkout-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.checkout-summary {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  font-size: 14px;
  color: #666;
}

.summary-item .total-price {
  font-size: 16px;
  font-weight: bold;
  color: #e74c3c;
}

@media (max-width: 768px) {
  .cart-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .cart-item .el-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .cart-item .el-col {
    width: 100% !important;
    text-align: center;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 20px;
  }
  
  .checkout-section {
    flex-direction: column;
    gap: 15px;
  }
}
</style> 